package com.blackhorse.anlis.anli_tx_aop;

import com.blackhorse.utils.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 使用Spring Aop完成之前转账案例中事务控制（注解配置）
 */
@Component("enableTransactionWithArroudAopAnno")
@Aspect
public class EnableTransactionWithArroudAopAnno {
    //切入无事务控制的service
    @Pointcut("execution(* com.blackhorse.anlis.anli.serviceImpl.AccountServiceImpl.*(..))")
    private void pt1(){}

    @Autowired
    @Qualifier("transactionManager_aop_annotation")
    private TransactionManager transactionManager;

    @Around("pt1()")
    public Object arroundTransaction(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try {
            transactionManager.beginTransaction();
            Object[] args = pjp.getArgs();
            rtValue = pjp.proceed(args);
            transactionManager.commit();
            return rtValue;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            transactionManager.rollback();
            return null;
        }finally {
            transactionManager.rollback();
        }
    }

}
